package com.biye.api.tool.ExcelTemplate;

import com.base.common.edu.entity.Department;
import com.base.common.edu.entity.Staff;
import com.base.common.edu.mapper.StaffMapper;
import com.base.common.edu.util.Dateutil;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;

@Transactional
public class TeaInfoImportThread implements Runnable{

    /***
     * 如果用了线程池，就不需要再使用信号量。根据时间情况使用synchronized(this)
     * ExecutorService executor = Executors.newFixedThreadPool(Thread_size);
      */
    private final Semaphore parallel = new Semaphore(10);

    private StaffMapper sd;
    private List<Staff> list;
    private Map<String, String> dept_mapping;
    private static SqlSessionFactory sqlSessionFactory;

    public TeaInfoImportThread(List<Staff> list, StaffMapper ud, SqlSessionFactory sqlSessionFactory, Map<String, String> dept_mapping){
        this.list = list;
        this.sd=ud;
        this.sqlSessionFactory=sqlSessionFactory;
        this.dept_mapping = dept_mapping;
    }

    @Override
    public void run() {
        synchronized(this){
            try {
                parallel.acquire();
                insert();
//                System.out.println("当前剩余通道数="+parallel.availablePermits());
                parallel.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void insert(){
        for ( Staff staff : list) {
            String dept_id = dept_mapping.get(staff.getDeptObject().getDeptName());
            Department dd = new Department();
            dd.setDeptId(dept_id);
            staff.setDeptObject(dd);
            // 首先根据身份证号查询是否有该职工信息
            Staff sta = new Staff();
            sta.setTno(staff.getTno());
            sta.setIdCard(staff.getIdCard());
            sta.setEmail(staff.getEmail());
            List<Staff> staff1 = sd.queryStaff(sta);
            // 若有该职工信息，则更新
            if ( staff1.size() > 0 ){
                String staff_id = staff1.get(0).getStaffId();
                staff.setStaffId(staff_id);
                sd.updateSatff(staff);
                break;
            }
            // 若没有则新增,同时判断邮箱是否被占用, 被占用则略过信息创建，并打印
            if ( sd.judgeIsItOccupied(staff.getTno(), staff.getIdCard(), staff.getEmail()) > 0 ) {
                System.out.println("该职工信息导入失败（学工号、身份证、邮箱号被占用）[Name：" + staff.getName() + "][userIdcard：" + staff.getIdCard() + "][userEmail：" + staff.getEmail() + "][Time：" + Dateutil.getCurrentDateText() + "]");
                break;
            }
            staff.setActivateStatus(1);
            sd.saveStaff(staff);
        }
    }

}
